<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select
          v-model="query.bisGsglId"
          placeholder="选择企业"
        >
          <el-option
            v-for="item in allGsgl"
            :key="item.bisGsglId"
            :label="item.bisGsglQymc"
            :value="item.bisGsglId"
          />
        </el-select>
        <el-input v-model="query.blurry" clearable size="small" placeholder="模糊搜索" style="width: 200px;" @keyup.enter.native="crud.toQuery" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="400px">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="所在公司" prop="bisJzdjKsmc">
          <el-select
            v-model="form.gsgl.bisGsglId"
            style="width: 250px"
            filterable
            placeholder="选择公司"
          >
            <el-option
              v-for="item in allGsgl"
              :key="item.bisGsglId"
              :label="item.bisGsglQymc"
              :value="item.bisGsglId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="bisRyglXm">
          <el-input v-model="form.bisRyglXm" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="性别" prop="bisRyglXb">
          <el-select v-model="form.bisRyglXb" filterable placeholder="请选择" style="width: 250px;">
            <el-option
              v-for="item in dict.xb"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证" prop="bisRyglZjhm">
          <el-input v-model="form.bisRyglZjhm" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="联系电话" prop="bisRyglLxdh">
          <el-input v-model="form.bisRyglLxdh" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="人员类型" prop="bisRyglRylx">
          <el-select v-model="form.bisRyglRylx" filterable placeholder="请选择" style="width: 250px;">
            <el-option
              v-for="item in dict.rylx"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.bisRyglJj" :rows="3" type="textarea" style="width: 250px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="faceFormVisible" title="维护头像" width="500px">
      <el-form label-width="80px">
        <el-form-item label="姓名" prop="xm">
          <el-input v-model="this.facePersonVo.xm" style="width: 180px;" disabled />
        </el-form-item>
        <el-form-item label="身份证" prop="sfz">
          <el-input v-model="this.facePersonVo.sfz" style="width: 180px;" disabled />
        </el-form-item>
        <el-form-item label="联系电话" prop="lxdh">
          <el-input v-model="this.facePersonVo.lxdh" style="width: 180px;" disabled />
        </el-form-item>
        <el-form-item label="定点编码" prop="ddbm">
          <el-input v-model="this.facePersonVo.ddbm" style="width: 180px;" disabled />
        </el-form-item>
        <el-form-item label="定点名称" prop="ddmc">
          <el-input v-model="this.facePersonVo.ddmc" style="width: 270px;" disabled />
        </el-form-item>
        <!-- 上传按钮 -->
        <el-upload
          ref="upload_shbzk"
          :data="fjlb"
          :headers="headers"
          :on-preview="handlePreview"
          :action="minioUploadFaceImageApi"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          :on-remove="handleRemove"
          :on-success="handleImgSuccess"
          :on-progress="handleProgress"
          :on-error="handleError"
          :file-list="file_list_nurselist"
          list-type="picture"
        >
          <el-button size="small" type="primary">上传头像</el-button>
          <div slot="tip" class="el-upload__tip">只能上传PNG、JPG、JPEG、BMP格式，且不超过5MB</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonStaus === 2" @click="faceFormVisible = false">取消</el-button>
        <el-button :loading="buttonStaus === 2" type="primary" @click="doUploadPerson()">确 定</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      size="small"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="gsgl.bisGsglQymc" label="单位" width="300" />
      <el-table-column prop="bisRyglXm" label="姓名" />
      <el-table-column prop="bisRyglLxdh" label="联系电话" />
      <el-table-column prop="bisRyglRylx" label="人员类型">
        <template slot-scope="scope">
          {{ dict.label.rylx[scope.row.bisRyglRylx] }}
        </template>
      </el-table-column>
      <el-table-column prop="bisRyglXb" label="性别">
        <template slot-scope="scope">
          {{ dict.label.xb[scope.row.bisRyglXb] }}
        </template>
      </el-table-column>
      <el-table-column prop="bisRyglZjhm" label="身份证" />
      <el-table-column v-if="checkPer(['admin','rygl:edit','rygl:del'])" label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
          />
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click.native.prevent="doOpenFace(scope.row)"
          >
            维护头像
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudRygl from '@/api/business/rygl'
import crudFile from '@/api/tools/localStorage'
import { queryAll } from '@/api/business/gsgl'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'

const defaultForm = { bisRyglId: null, bisRyglUserId: null, gsgl: { bisGsglId: null }, bisRyglDw: null, bisRyglXm: null, bisRyglXb: null, bisRyglNl: null, bisRyglLxdh: null, bisRyglZjhm: null, bisRyglRylx: null, bisRyglJj: null, ywlx: null, lrr: null, lrrxm: null, lrbm: null, lrbmmc: null, lrsj: null, gxr: null, gxrxm: null, gxrbm: null, gxrbmmc: null, gxsj: null, sfyx: null }
export default {
  name: 'Rygl',
  // eslint-disable-next-line vue/no-unused-components
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['xb', 'rylx'],
  cruds() {
    return CRUD({ title: '人员管理', url: 'api/rygl', idField: 'bisRyglId', sort: 'bisRyglId,desc', crudMethod: { ...crudRygl }})
  },
  data() {
    return {
      allGsgl: [],
      faceFormVisible: false,
      buttonStaus: 1,
      isUpload: false,
      facePersonVo: {
        ddmc: '',
        ddbm: '',
        xm: '',
        sfz: '',
        lxdh: '',
        userId: '',
        xb: '',
        fileIds: ''
      },
      headers: { 'Authorization': getToken() },
      isSuccess: false,
      fileUploading: false,
      fileIds: '',
      /* 上传附件时，附件类别（照护解约） */
      fjlb: { 'fjlb': 'nurselist' },
      file_list_nurselist: [],
      permission: {
        add: ['admin', 'rygl:add'],
        edit: ['admin', 'rygl:edit'],
        del: ['admin', 'rygl:del']
      }
    }
  },
  created() {
    this.queryAll()
  },
  computed: {
    ...mapGetters([
      'minioUploadFaceImageApi',
      'user'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 获取所有公司
    queryAll() {
      queryAll().then(res => {
        this.allGsgl = res
        console.log(this.allHljg)
      }).catch(() => { })
    },
    doOpenFace(row) {
      this.fileIds = ''
      this.file_list_nurselist = []
      this.isUpload = true
      this.facePersonVo.ddmc = row.gsgl.bisGsglQymc
      this.facePersonVo.ddbm = row.gsgl.bisGsglYljgdm
      this.facePersonVo.xm = row.bisRyglXm
      this.facePersonVo.sfz = row.bisRyglZjhm
      this.facePersonVo.lxdh = row.bisRyglLxdh
      this.facePersonVo.userId = row.bisRyglUserId
      this.facePersonVo.xb = row.bisRyglXb === '0' ? '1' : '2'
      this.faceFormVisible = true
      this.getFiles(this.facePersonVo.userId)
    },
    doUploadPerson() {
      if (this.fileIds === undefined || this.fileIds === '') {
        this.$notify({
          title: '请上传头像',
          type: 'warning',
          duration: 2500
        })
        return
      }
      this.facePersonVo.fileIds = this.fileIds

      this.buttonStaus = 2
      crudRygl.faceCreatePerson(this.facePersonVo)
        .then(res => {
          this.$notify({
            title: '操作成功',
            type: 'success',
            duration: 2500
          })
          this.faceFormVisible = false
          this.buttonStaus = 1
        })
        .catch(err => {
          this.buttonStaus = 1
          console.log(err)
        })
    },
    /**
     * 修改操作时，需要加载附件信息
     */
    getFiles(ywid) {
      crudFile.queryFileByFjlb2(ywid).then(res => {
        for (let i = 0; i < res.length; i++) {
          const file = res[i]
          if (file.fjlb === 'nurselist') {
            const obj = { 'id': file.id, 'name': file.name, 'url': file.path2 }
            this.file_list_nurselist.push(obj)
            this.fileIds += file.id + ','
            this.isUpload = false
          }
        }
      })
    },
    /**
     * 上传前校验
     * @param file
     * @returns {boolean}
     */
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
      //  this.loading = false
        this.$message.error('上传文件大小不能超过 5MB!' + (file.size / 1024 / 1024))
      }
      return isLt2M
    },
    /**
     * 删除前确认提示
     * @param file
     * @returns {Promise<MessageBoxData>}
     */
    beforeRemove(file) {
      console.log('删除前确认提示 :{}', file)
      return this.$confirm(`删除操作会直接删除此图片，确定删除 ${file.name}？`)
    },
    /**
     * 图片上传成功时的钩子
     * @param response
     * @param file
     * @param fileList
     */
    handleImgSuccess(response, file, fileList) {
      console.log('文件上传成功时的钩子response :{}, file{}', response, file)
      this.fileIds += response.data.id + ','
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.isSuccess = true
      this.fileUploading = false
    },
    handleProgress(event) {
      console.log(event)
      this.fileUploading = true
    },
    /**
     * 监听上传失败
     * @param e
     * @param file
     * @param fileList
     */
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      // this.loading = false
    },
    /**
     * 移除文件
     * @param file
     * @param fileList
     */
    handleRemove(file, fileList) {
      console.log('移除文件 :{}===================', file, fileList)
    //  crudFile.del([file.response.data.id]).then(res => {})
    },
    /**
     * 图片预览
     * @param file
     */
    handlePreview(file) {
      console.log('图片预览 :{}', file)
      if (file.response) {
        window.open(file.response.data.url2)
      } else {
        window.open(file.url)
      }
    }
  }
}
</script>

<style scoped>

</style>
